import {gsap} from "gsap";
import {getControlState} from "@/views/HomePage/modelCanvas/threeJSUtil/getControlState";

let lastGsp = null;
export const roamView = ({controls, from, to, duration = 3, ease = "linear", onComplete}) => {
  return new Promise((resolve) => {
  if (duration === 0) {
    controls.target.set(to.tx, to.ty, to.tz);
    controls.object.position.set(to.px, to.py, to.pz);
    controls.update();
    resolve()
    return;
  }
  const f = from || getControlState(controls);
  // 如果一致，则不进行漫游，避免画面出现假死状态
  if (f.tx === to.tx && f.ty === to.ty && f.tz === to.tz && f.px === to.px && f.py === to.py && f.pz === to.pz) {
    resolve()
    return;
  }
  lastGsp && lastGsp.kill();
  lastGsp = gsap.to(f, {
    ...to,
    duration,
    onStart() {
      controls.enabled = false;
    },
    onUpdate: () => {
      controls.target.set(f.tx, f.ty, f.tz);
      controls.object.position.set(f.px, f.py, f.pz);
      controls.update();
    },
    onComplete() {
      controls.enabled = true;
      resolve()
      onComplete && onComplete();
    },
    ease,
  });
  })

};
export const roamViewSequence = ({controls, viewpoints, ease = "power2.inOut", onComplete}) => {
  const queue = [...viewpoints];
  let currentAnimation = null;
  const target = controls.target;
  const position = controls.object.position;
  // 保存初始状态作为起点
  let startState = {
    tx: target.x,
    ty: target.y,
    tz: target.z,
    px: position.x,
    py: position.y,
    pz: position.z
  };

  const playNext = () => {
    if (queue.length === 0) {
      controls.enabled = true;
      onComplete?.();
      return;
    }

    const config = queue.shift();
    const targetView = config.viewpoints;
    const duration = config.duration;

    // 跳过相同位置（比较上一个终点和新目标点）
    if (startState.tx === targetView.tx &&
      startState.ty === targetView.ty &&
      startState.tz === targetView.tz &&
      startState.px === targetView.px &&
      startState.py === targetView.py &&
      startState.pz === targetView.pz) {
      playNext();
      return;
    }

    if (duration === 0) {
      // 立即跳转时更新起点状态
      startState = {...targetView};
      controls.target.set(targetView.tx, targetView.ty, targetView.tz);
      controls.object.position.set(targetView.px, targetView.py, targetView.pz);
      controls.update();
      playNext();
      return;
    }

    currentAnimation = gsap.to(startState, {
      ...targetView,
      duration,
      ease: config.ease || ease,
      onStart: () => controls.enabled = false,
      onUpdate: () => {
        controls.target.set(startState.tx, startState.ty, startState.tz);
        controls.object.position.set(startState.px, startState.py, startState.pz);
        controls.update();
      },
      onComplete: () => {
        // 动画完成后，将当前状态保存为下一个动画的起点
        startState = {...startState}; // 复制最终状态
        playNext();
      }
    });
  };

  playNext();

  return () => {
    currentAnimation?.kill();
    controls.enabled = true;
  };
};
